package com.shiwenping.reply.net;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.shiwenping.reply.net.service.AllService;
import com.shiwenping.reply.tools.AllUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
import retrofit2.Response;
import rx.Observable;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * @author shiwenping
 * @date 17-11-10 下午6:23
 */

public class RxDownLoadManager {
    public static interface RxDownLoadCallBack {
        /**
         * 需要下载的集合
         *
         * @return
         */
        String getUrl();

        String getFileName();

        /**
         * tag
         *
         * @return
         */
        Object tag();
    }


    public static Observable<String> download( String url) {
        return Observable.just(url)
                .flatMap(s -> {
                    File file = new File(AllUtils.toFileSavePath(s));
                    boolean is = !TextUtils.isEmpty(s) && !file.exists();
//                    Log.d("HaiChecker", Environment.getExternalStoragePublicDirectory("") + "/reply/file/" + AllUtils.urlToFileName(s));
//                    Log.d("HaiChecker", file.exists() + "");
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                    }
                    if (!file.exists()) {
                        try {
                            file.createNewFile();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (!is)
                    {
                        return Observable.just(s);
                    }
                    Log.d("HaiChecker",s);
                    OkHttpClient okHttpClient = new OkHttpClient();
                    Request request = new Request.Builder().url(s).build();
                    Call call = okHttpClient.newCall(request);
                    okhttp3.Response response = null;
                    try {
                        response = call.execute();
                        if (response.isSuccessful()) {
                            Log.d("HaiChecker",response.code()+"");
                            writeFileToSDCard(response.body(),  AllUtils.toFileSavePath(s));
                        }else {
                            Log.d("HaiChecker",response.message());
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        if (response != null) {
                            response.close();
                        }
                    }
                    return Observable.just(s);
                }).subscribeOn(Schedulers.io());
    }


    public static Observable<RxDownLoadCallBack> download(RxDownLoadCallBack rxDownLoadCallBack) {
        return Observable.just(rxDownLoadCallBack)
                .flatMap(s -> {
                    File file = new File(Environment.getExternalStoragePublicDirectory("") + "/reply/file/" + AllUtils.urlToFileName(s.getFileName()));
                    boolean is = !TextUtils.isEmpty(s.getUrl()) && !file.exists();
//                    Log.d("HaiChecker", Environment.getExternalStoragePublicDirectory("") + "/reply/file/" + AllUtils.urlToFileName(s));
//                    Log.d("HaiChecker", file.exists() + "");
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                    }
                    if (!file.exists()) {
                        try {
                            file.createNewFile();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (!is)
                    {
                        return Observable.just(s);
                    }
                    Log.d("HaiChecker",s.getFileName());
                    OkHttpClient okHttpClient = new OkHttpClient();
                    Request request = new Request.Builder().url(s.getUrl()).build();
                    Call call = okHttpClient.newCall(request);
                    okhttp3.Response response = null;
                    try {
                        response = call.execute();
                        if (response.isSuccessful()) {
                            Log.d("HaiChecker",response.code()+"");
                            writeFileToSDCard(response.body(),  AllUtils.urlToFileName(s.getUrl()));
                        }else {
                            Log.d("HaiChecker",response.message());
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        if (response != null) {
                            response.close();
                        }
                    }
                    return Observable.just(s);
                }).subscribeOn(Schedulers.io());
    }

    /**
     * 保存到文件
     * @param body  内容
     * @param filePath  文件路径
     * @return
     */
    public static boolean writeFileToSDCard(ResponseBody body,String filePath) {
        try {
            // todo change the file location/name according to your needs
            File futureStudioIconFile = new File(filePath);
            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                byte[] fileReader = new byte[4096];
                long fileSize = body.contentLength();
                long fileSizeDownloaded = 0;
                inputStream = body.byteStream();
                outputStream = new FileOutputStream(futureStudioIconFile);
                while (true) {
                    int read = inputStream.read(fileReader);
                    if (read == -1) {
                        break;
                    }
                    outputStream.write(fileReader, 0, read);
                    fileSizeDownloaded += read;
//                    Log.d("HaiChecker", "file download: " + fileSizeDownloaded + " of " + fileSize);
                }
                outputStream.flush();
                return true;
            } catch (IOException e) {
                return false;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            }
        } catch (IOException e) {
            return false;
        }
    }
}
